/**
 * 发起支付前确认订单弹窗
 */
import React, { useEffect, useState } from 'react';
import { Descriptions, Modal, Divider, Button } from 'antd'
import { showMsg, isNull } from '@/utils/utils';
import { updateOnceOrderStatus } from '@/services/order/api';
import ProTable from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import Result from './comm/Result';
import { museText } from './Detail';

const PayDialog: React.FC<any> = (props) => {
  const {
    patientInfo = {},
    handleModalVisible,
    goodsList = [],
    settleInfo = {},
    reload,
  } = props;
  // 发起支付的结果弹窗
  const [showResult, setShowResult] = useState(false);
  const [loading, setLoading] = useState(false);
  // 商品原价
  const [goodsTotalPrice, setGoodsTotalPrice] = useState<number>(0);
  // 商品折扣
  const [goodsDisaccountPrice, setGoodsDisaccountPrice] = useState<number>(0);
  // 商品数量
  const [goodsNum, setGoodsNum] = useState<number>(0);
  // 验光数据
  const [ygData, setYgData] = useState([]);

  const columns: ProColumns<any>[] = [
    {
      title: '分类',
      dataIndex: 'class_name'
    },
    {
      title: '品牌',
      dataIndex: 'brand_name'
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name'
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id'
    },
    {
      title: '规格（单位）',
      dataIndex: 'specs_name'
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      valueType: 'money',
      align: 'right',
      width: 90
    },
    {
      title: '原价',
      dataIndex: 'goods_total_price',
      valueType: 'money',
      align: 'right',
      width: 90
    },
    {
      title: '数量',
      dataIndex: 'goods_num'
    },
    {
      title: '折扣',
      dataIndex: 'discount'
    },
    {
      title: '折扣价',
      dataIndex: 'discount_price',
      valueType: 'money',
      align: 'right',
      width: 90
    }
  ]

  const columns_eye: ProColumns[] = [
    {
      title: '',
      dataIndex: 'c1',
      align: 'center',
      width: 110
    },
    {
      title: '球镜',
      dataIndex: 'c2',
      align: 'center',
      width: 100
    },
    {
      title: '柱镜',
      dataIndex: 'c3',
      align: 'center',
      width: 100
    },
    {
      title: '轴位',
      dataIndex: 'c4',
      align: 'center',
      width: 100
    },
    {
      title: '矫正前视力',
      dataIndex: 'c5',
      align: 'center',
      width: 100
    },
    {
      title: '矫正后视力',
      dataIndex: 'c6',
      align: 'center',
      width: 100
    },
    {
      title: '瞳距',
      dataIndex: 'c7',
      align: 'center',
      width: 100
    },
    {
      title: '总瞳距',
      dataIndex: 'c8',
      align: 'center',
      width: 100,
      render: (value, row, index) => ({
        children: <div style={{ textAlign: 'center' }}>{value}</div>,
        props: { rowSpan: index === 0 ? 2 : 0 }
      })
    },
    {
      title: '瞳高',
      dataIndex: 'c9',
      align: 'center',
      width: 100
    },
    {
      title: '离焦量',
      dataIndex: 'c11',
      align: 'center',
      width: 100
    },
    {
      title: 'ADD',
      dataIndex: 'c12',
      align: 'center',
      width: 100,
      render: (value, row, index) => ({
        children: <div style={{ textAlign: 'center' }}>{value}</div>,
        props: { rowSpan: index === 0 ? 2 : 0 }
      })
    }
  ];

  // 格式化验光数据
  const formatData = (value) => {
    return isNull(value) ? '无' : parseFloat(value) >= 0 ? `+${parseFloat(value).toFixed(2)}` : parseFloat(value).toFixed(2)
  }

  // 发起支付
  const startPay = async () => {
    setLoading(true);
    updateOnceOrderStatus({
      order_id: settleInfo.order_id,
      order_status: 'W'
    }).then(() => {
      setLoading(false);
      setShowResult(true);
    }).catch((error) => {
      setLoading(false);
      showMsg(error?.data?.errmsg);
    })
  }

  useEffect(() => {
    // console.info('::::: ', patientInfo);
    if (goodsList.length) {
      let sumprice = 0, disprice = 0, num = 0;
      goodsList.forEach(item => {
        sumprice += Number(item.goods_total_price as number);
        setGoodsTotalPrice(sumprice);

        disprice += Number(item.discount_price);
        setGoodsDisaccountPrice(disprice);

        num += item.goods_num;
        setGoodsNum(num);
      })
    }
    const data = [{
      c1: '右眼（R）',
      c2: formatData(settleInfo.right_degrees),
      c3: formatData(settleInfo.right_astig),
      c4: settleInfo.right_axial,
      c5: settleInfo.right_rectify_bef,
      c6: settleInfo.right_rectify_af,
      c7: settleInfo.pup_distance_right,
      c8: settleInfo.pup_distance,
      c9: settleInfo.pup_high_right,
      c11: settleInfo.right_defocus,
      c12: settleInfo.madd
    }, {
      c1: '左眼（L）',
      c2: formatData(settleInfo.left_degrees),
      c3: formatData(settleInfo.left_astig),
      c4: settleInfo.left_axial,
      c5: settleInfo.left_rectify_bef,
      c6: settleInfo.left_rectify_af,
      c7: settleInfo.pup_distance_left,
      c8: settleInfo.pup_distance,
      c9: settleInfo.pup_high_left,
      c11: settleInfo.left_defocus,
      c12: settleInfo.madd
    }];
    if (!isNull(settleInfo.refund_service_price) && parseFloat(settleInfo.refund_service_price) > 0) {
      settleInfo.refund_order_goods_list.push({ id: '10086', goods_name: '配镜服务费', goods_total_price: settleInfo.refund_service_price });
    }
    setYgData(data);
  }, [goodsList])

  // 判断是否需要显示配镜数据
  const getIsShow = () => {
    if (!isNull(settleInfo.left_degrees) || !isNull(settleInfo.left_astig) || !isNull(settleInfo.left_axial) || !isNull(settleInfo.right_degrees) || !isNull(settleInfo.right_astig) || !isNull(settleInfo.right_axial) || !isNull(settleInfo.pup_distance) || !isNull(settleInfo.after_left_version) || !isNull(settleInfo.after_right_version) || !isNull(settleInfo.before_left_version) || !isNull(settleInfo.before_right_version)) {
      return true;
    }
    return false;
  }

  // 判断是否需要显示镜架数据
  const getFrameIsShow = () => {
    if (!isNull(settleInfo.frame_back) || !isNull(settleInfo.frame_diagonal) || !isNull(settleInfo.frame_height) || !isNull(settleInfo.frame_middle) || !isNull(settleInfo.frame_width)) {
      return true;
    }
    return false;
  }

  // 判断是否需要显示随访数据
  const getSurveyIsShow = () => {
    if (!isNull(settleInfo.survey_title) || !isNull(settleInfo.survey_date)) {
      return true;
    }
    return false;
  }

  let no = 3;
  return <Modal
    title="查看订单"
    width="90%"
    bodyStyle={{ height: window.innerHeight - 185, overflowY: 'scroll' }}
    maskClosable={false}
    onCancel={() => handleModalVisible(false)}
    footer={[
      <Button key="close" onClick={() => {
        handleModalVisible(false);
      }}>
        关闭
      </Button>,
      <Button loading={loading} key="pay" type="primary" onClick={() => {
        startPay()
      }}>
        发起支付
      </Button>
    ]}
    visible>
    <div className="dialog">
      <div className='common_title'>1.患者信息</div>
      <Divider style={{ margin: '10px 0' }} />
      <Descriptions column={4}>
        <Descriptions.Item label="身份证/住院号">
          {patientInfo.admission_num}{patientInfo.admission_num && patientInfo.identity_no ? ' / ' : ''}{patientInfo.identity_no}
        </Descriptions.Item>
        <Descriptions.Item label="患者姓名">
          {patientInfo.patient_name}
        </Descriptions.Item>
        <Descriptions.Item label="患者性别">{patientInfo.patient_sex_name || '-'}</Descriptions.Item>
        <Descriptions.Item label="归属科室">
          {patientInfo.create_dept_name || settleInfo.create_dept_name}
        </Descriptions.Item>
      </Descriptions>

      <div className='common_title'>2.商品信息</div>
      <Divider style={{ margin: '10px 0' }} />
      <ProTable<STOCKGOODSAPI.GoodsItem>
        rowKey="goods_id"
        columns={columns}
        options={false}
        search={false}
        pagination={false}
        scroll={{ x: 1000 }}
        dataSource={goodsList}
        bordered />

      {
        // 展示验光信息数据
        getIsShow() &&
        <>
          <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.验光信息`}</div>
          <Divider />
          <ProTable
            rowKey="id"
            size='small'
            bordered
            // style={{ margin: '0 -24px' }}
            columns={columns_eye}
            // actionRef={actionRef1}
            search={false}
            options={false}
            dataSource={ygData}
            pagination={false}
          />
          <Descriptions column={4}>
            <Descriptions.Item span={1} label="用途">{museText[settleInfo?.muse] || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="验光号">{settleInfo.sight_no || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="就诊医生">{settleInfo.doctor_name || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="验光师">{settleInfo.optician_name || '-'}</Descriptions.Item>
            <Descriptions.Item span={3} label="特殊备注">{settleInfo.special_case || '-'}</Descriptions.Item>
          </Descriptions>
        </>
      }

      {
        getFrameIsShow() &&
        <>
          <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.镜架信息`}</div>
          <Divider />
          <Descriptions column={4}>
            <Descriptions.Item span={1} label="框宽">{settleInfo.frame_width || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="框高">{settleInfo.frame_height || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="中梁">{settleInfo.frame_middle || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="镜对角直径">{settleInfo.frame_diagonal || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="型号">{settleInfo.frame_model || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="框型">{settleInfo.frame_material || '-'}</Descriptions.Item>
            <Descriptions.Item span={1} label="是否需要防滑套">{settleInfo.is_slip === 'Y' ? '需要' : '不需要'}</Descriptions.Item>
            <Descriptions.Item span={1} label="是否自备镜架">
              {(settleInfo.frame_flag ?? '0') == '0' ? '非自备' : (settleInfo.frame_flag == '1' ? '自备/留' : '自备/未留')}
            </Descriptions.Item>
          </Descriptions>
        </>
      }

      <div className='common_title' style={{ marginTop: 10 }}>{`${no++}.结算信息`}</div>
      <Divider style={{ margin: '10px 0' }} />
      <Descriptions>
        <Descriptions.Item label="订单编号">{settleInfo.order_id}</Descriptions.Item>
        <Descriptions.Item label="创建时间">{settleInfo.create_date + ' ' + settleInfo.create_time}</Descriptions.Item>
        {
          settleInfo.settle_no && <Descriptions.Item label="结算单号">{settleInfo.settle_no}</Descriptions.Item>
        }
        {
          settleInfo.pay_time && <Descriptions.Item span={2} label="支付时间">{settleInfo.pay_time}</Descriptions.Item>
        }

        <Descriptions.Item label="商品原价">{goodsTotalPrice}（元）</Descriptions.Item>
        <Descriptions.Item label="商品数量">
          <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{goodsNum}</span>（件）
        </Descriptions.Item>
        <Descriptions.Item label="订单金额">{goodsDisaccountPrice}（元）</Descriptions.Item>
        <Descriptions.Item label="订单折扣">
          <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{settleInfo.discount_ratio}</span>
        </Descriptions.Item>
        <Descriptions.Item label="欠款">{parseFloat(settleInfo.owing_price ?? 0).toFixed(2)}（元）</Descriptions.Item>
        <Descriptions.Item label="邮寄费用">{parseFloat(settleInfo.franking ?? 0).toFixed(2)}（元）</Descriptions.Item>
        <Descriptions.Item label="结算价格">
          <span style={{ color: '#F5232D', fontWeight: 'bold' }}>{settleInfo.sett_price}</span>（元）
        </Descriptions.Item>
        <Descriptions.Item label="已开具发票">{settleInfo.is_ballot === 'Y' ? '已开具' : '未开'}</Descriptions.Item>
        <Descriptions.Item label="邮寄地址">{settleInfo.frank_address}</Descriptions.Item>
        <Descriptions.Item label="订单备注1">{settleInfo.remarks || '无'}</Descriptions.Item>
        <Descriptions.Item label="订单备注2">{settleInfo.sec_remarks || '无'}</Descriptions.Item>
      </Descriptions>

      {
        getSurveyIsShow() &&
        <>
          <div style={{ marginTop: 15, fontSize: 12, fontWeight: 'bold' }}>{`${no++}.患者调研`}</div>
          <Divider />
          <Descriptions style={{ marginTop: 10 }} column={4}>
            <Descriptions.Item label="随访调研表">{settleInfo.survey_title}</Descriptions.Item>
            <Descriptions.Item label="随访时间">{settleInfo.survey_date}</Descriptions.Item>
          </Descriptions>
        </>
      }
    </div>
    {
      // 展示支付二维码弹窗
      showResult &&
      <Result
        id={settleInfo.order_id}
        onClose={() => {
          setShowResult(false);
          reload(false);
          // history.replace(`/order/one-time-order`);
          // if (type === 'read') {
          //   // onClose(true);
          //   // 关闭弹窗
          // } else {
          //   history.replace(`/order`);
          //   // 这里返回到订单列表
          // }
        }}
        onPrint={() => {
          reload(true);
          // 这里调用打印
        }}
      />
    }
  </Modal>
}
export default PayDialog;
